package com.yubest.junit.topdf;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * aspose word转pdf
 *
 * @Author: hweiyu
 * @Date: 2022/11/18 11:42
 */
public class AsposeWordToPdf implements ToPdf {

    static {
        try (InputStream is = AsposeWordToPdf.class.getClassLoader().getResourceAsStream("aspose-license.xml")) {
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] to(byte[] bytes) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();
             ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            //Address是将要被转化的word文档
            Document doc = new Document(is);
            String nameOfApplication = doc.getBuiltInDocumentProperties().get("NameOfApplication").getValue().toString();
            if(nameOfApplication.toUpperCase().contains("WPS")){
                doc.getStyles().get("Normal").getParagraphFormat().setSpaceAfter(0);
            }
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.PDF);
            return os.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
